#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/socket.h>
#include <string.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/shm.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/stat.h>
#define SEND_OK 0xAA
#include <pthread.h>
#include <stdint.h>

#define N 32


void serial_init(int fd)
{
	struct termios options;
	tcgetattr(fd, &options);
	options.c_cflag |= ( CLOCAL | CREAD );
	options.c_cflag &= ~CSIZE;
	options.c_cflag &= ~CRTSCTS;
	options.c_cflag |= CS8;
	options.c_cflag &= ~CSTOPB;
	options.c_iflag |= IGNPAR;
	options.c_iflag &= ~(ICRNL | IXON);
	options.c_oflag = 0;
	options.c_lflag = 0;
	cfsetispeed(&options, B115200);
	cfsetospeed(&options, B115200);
	tcsetattr(fd,TCSANOW,&options);
}
struct msg
{
	long type;
	unsigned char text[N];
};

struct msg msg_buf = {0, {0}};

int main(int argc, const char *argv[])
{
	key_t key; 
	int msgid; 
	char device[6] = {0};

	memset(&msg_buf, 0, sizeof(msg_buf));
	int dev_uart_fd;
	if((dev_uart_fd = open("/dev/ttyUSB0", O_RDWR)) < 0)
	{
		perror("uart uart err");
		return -1;
	}
	serial_init(dev_uart_fd);

	if((key = ftok("/", 'b')) < 0)
	{
		perror("ftok");
		exit(1);
	}

	msgid = msgget(key,IPC_CREAT|IPC_EXCL|0666);
	if(msgid == -1)
	{
		if(errno == EEXIST)
		{
			msgid = msgget(key, 0666);
		}
		else{
		perror("msgget");
		exit(1);
		}
	}
	
	while(1)
	{
	msgrcv(msgid, &msg_buf, sizeof(msg_buf) - sizeof(long), 1L, 0);
	printf("recv:%x", msg_buf.text[0]);	
	
	if(msg_buf.text[0] == 0x80)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);  //关闭风扇
	}

	if(msg_buf.text[0] == 0x81)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //一档
	}

	if(msg_buf.text[0] == 0x82)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //二档
	}

	if(msg_buf.text[0] == 0x83)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //三当
	}

	if(msg_buf.text[0] == 0x90)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //蜂鸣器关闭
	}
	if(msg_buf.text[0] == 0x91)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //打开
	}
	if(msg_buf.text[0] == 0x92)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //自动报警关闭
	}

	if(msg_buf.text[0] == 0x93)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //自动报警打开
	}


	if(msg_buf.text[0] == 0xa0)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //灯关


	}

	if(msg_buf.text[0] == 0xa1)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //灯开
	}


	if(msg_buf.text[0] == 0xbf)
	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //数码管关
	}



	if(msg_buf.text[0] == 0xb0)

	{
		write(dev_uart_fd, &msg_buf.text[0], 1);   //数码管0
	}
	}
	}





